<?php
class AdminAction extends PiscesAction
{
	public function __construct()
	{
		parent::__construct();
	}
	
	public function beforeExecute()
	{
		parent::beforeExecute();
		
		$this->context->adminId	= 0;
		$authCode	= C('LtCookie')->getCookie('admin_auth');
		if ($authCode)
		{
			list($id, $password, $ip) = explode("\t", $authCode);
			$adminService	= new AdminService();
			$admin	= $adminService->get($id);
			if ($admin && $admin['password'] == $password && (!$this->data['site']['ipcheck'] || $ip==$this->getIp()))
			{
				$this->data['user']	= $admin;
				$this->context->adminId	= $admin['id'];
			}
			else
			{
				$this->data['user'] = false;
				C('LtCookie')->delCookie('admin_auth');
			}
		}
		if (!$this->context->adminId)
		{
			if($this->responseType=='json')
			{
				$this->data['data']['loginUrl']	= C('LtUrl')->generate('Default', 'Login');
				$this->writeResponse();
				exit;
			}
			else
			{
				$this->redirect(C('LtUrl')->generate('Default', 'Login'));
			}
		}
	}
	
	public function error($code)
	{
		if($code==404)
		{
			$this->redirect($this->data['baseurl'].'404.html');
		}
	}
	
	protected function upload($uploadName,$uploadDir,$fileName='',$small=0, $smallConf=array())
	{
		$upload		= new UploadService($uploadDir);
		$ret		= $upload->upload($this->context,$uploadName,$fileName,$small, $smallConf);
		$fileName	= '';
		$res		= array('code'=>0,'file'=>'','message'=>'');
		switch($ret)
		{
			case 1:
				$res['code']	= 1;
				$res['message']	= '上传文件不能为空';
				break;
			case 2:
				$res['code']	= 2;
				$res['message']	= '无效的文件格式';
				break;
			case 3:
				$res['code']	= 3;
				$res['message']	= '超过了上传的最大尺寸';
				break;
			case 4:
				$res['code']	= 4;
				$res['message']	= '上传失败';
				break;
			case 0:
				$res['file']	= $upload->getUploadFileName();
		}
		return $res;
	}
	
	protected function getUploadDir()
	{
		return APP_WEB_PATH.'images/upload/';
	}
	
	protected function getUploadUrl()
	{
		return 'images/upload/';
	}
}